package admin

import (
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/pkg/utils"
	"github.com/flosch/pongo2"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
)

type Blog struct {
	Base
}

func (b *Blog) Index(c *gin.Context) {
	c.HTML(200, "admin/blog/index.html", pongo2.Context{
		"title": "Welcome11222!",
		"greet": "hello",
		"obj":   "world",
	})
}

// List 列表
func (b *Blog) List(c *gin.Context) {
	data := make(map[string]interface{})

	pageNum, _ := strconv.Atoi(c.Query("page"))

	title := c.Query("title")
	maps := "title like '%" + title + "%'"

	data["rows"] = service.Blog.BlogList(pageNum, utils.PageSize, maps)
	data["total"] = service.Blog.GetBlogTotal(maps)

	response.Success(c, data, "列表返回成功了呀！")
}

// Detail 详情
func (b *Blog) Detail(c *gin.Context) {
	data := make(map[string]interface{})

	id, _ := strconv.Atoi(c.Param("id"))
	data["rows"], _ = service.Blog.BlogDetail(id)

	response.Success(c, data)
}

// Category 种类渲染页面
func (b *Blog) Category(c *gin.Context) {
	response.HTML(c, "category/index", nil)
}

// CategoryList 获取列表数据
func (b *Blog) CategoryList(c *gin.Context) {
	data := make(map[string]interface{})
	data["rows"] = service.Category.GetBlogCategoryList("4")

	response.Success(c, data)
}

// Edit 文章新增、编辑
func (b *Blog) Edit(c *gin.Context) {
	response.HTML(c, "blog/edit", nil)
}

// EditMd markdown文章新增、编辑
func (b *Blog) EditMd(c *gin.Context) {
	response.HTML(c, "blog/md", nil)
}

// Insert 新增保存
func (b *Blog) Insert(c *gin.Context) {
	blog := &model.Blog{}

	if err := c.ShouldBind(&blog); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.Blog.Create(blog)

	if err != nil {
		logrus.Error("修改失败", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, blog)
}

// Update 修改
func (b *Blog) Update(c *gin.Context) {
	blog := &model.Blog{}

	if err := c.ShouldBind(&blog); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	id := strconv.Itoa(blog.Id)
	err := service.Blog.Update(id, blog)

	if err != nil {
		logrus.Error("修改失败", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	response.Success(c, blog)
}

// Destory 删除
func (b *Blog) Destory(c *gin.Context) {
	id := c.PostForm("id")
	service.Blog.Delete(id)

	response.Success(c, id)
}
